package org.example.curriculum_design_6_16.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import org.example.curriculum_design_6_16.entity.dto.UserFormDTO;
import org.example.curriculum_design_6_16.entity.pojo.Student;
import org.example.curriculum_design_6_16.entity.pojo.User;
import org.example.curriculum_design_6_16.entity.vo.Result;
import org.example.curriculum_design_6_16.mapper.*;
import org.example.curriculum_design_6_16.service.RedisService;
import org.example.curriculum_design_6_16.service.RoleService;
import org.example.curriculum_design_6_16.service.StudentService;
import org.example.curriculum_design_6_16.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RoleService roleService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;


    @Override
    public User createUserWithDefaultRole(UserFormDTO userFormDTO) {
        // 创建用户实体
        User user = new User();
        user.setUserId(userFormDTO.getUserid());
        user.setUsername(userFormDTO.getUsername());
        user.setPasswordHash(passwordEncoder.encode(userFormDTO.getPassword()));
        user.setEmail(userFormDTO.getEmail());
        user.setPhone(userFormDTO.getPhone());
        user.setRealName(userFormDTO.getRealName());
        user.setCreatedAt(new Date());
        user.setIsActive(1); // 默认激活

        // 保存用户到user表
        this.save(user);

        // 分配默认角色（普通用户，角色ID为"2"）
        roleService.assignDefaultRole(user.getUserId());

        return user;
    }

    @Override
    public Result validateUserData(UserFormDTO validator) {
        // 先判断元素是否有空
        if (validator.getUserid().isEmpty() || validator.getUsername().isEmpty() || validator.getEmail().isEmpty()
                || validator.getPassword().isEmpty()) {
            return Result.fail(410, "填写的账号内容缺失,请检查");
        }
        if (!validator.getUserid().matches("^\\S{5,16}$")) {
            return Result.fail(412, "用户名格式错误");
        }
        if (!validator.getUsername().matches("^\\S{5,16}$")) {
            return Result.fail(412, "用户名格式错误");
        }
        if (!validator.getPassword().matches("^\\S{5,16}$")) {
            return Result.fail(413, "密码格式错误");
        }
        if (validator.getCode().isEmpty()) {
            return Result.fail(411, "请获取验证码");
        }
        Result result = this.EmailDataCheck(validator.getEmail(), validator.getCode());
        if(result.getStatus() != 200) {
            return Result.fail(result.getStatus(), result.getMsg());
        }
        Student student = studentService.getStudentById(validator.getUserid());
        if(student == null) {
            return Result.fail(415, "未查询到该学号");
        }
        // 使用 QueryWrapper 判断是否有重复的用户名、邮箱或昵称
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 确保字段非空并且使用正确的 getter 方法
        if (StrUtil.isNotBlank(validator.getUsername())) {
            wrapper.eq("username", validator.getUsername().trim()); // 去掉多余的空格
        }
        if (StrUtil.isNotBlank(validator.getEmail())) {
            wrapper.eq("email", validator.getEmail().trim()); // 去掉多余的空格
        }
        if (StrUtil.isNotBlank(validator.getRealName())) {
            wrapper.eq("real_name", validator.getRealName().trim()); // 去掉多余的空格
        }

        if (userMapper.existsByUsername(validator.getUsername())) {
            return Result.fail(415, "用户名已存在");
        }
        if (userMapper.existsByEmail(validator.getEmail())) {
            return Result.fail(416, "邮箱已被使用");
        }
        List<User> users = userMapper.selectList(wrapper);  // 使用正确的实体类进行查询
        // 遍历查找是否存在重复的用户名、邮箱或昵称
        for (User u : users) {
            if (u.getUsername() != null && u.getUsername().equalsIgnoreCase(validator.getUsername())) {
                return Result.fail(415, "用户已存在,请更换其他账号进行注册");
            }
            if (u.getEmail() != null && u.getEmail().equals(validator.getEmail())) {
                return Result.fail(416, "邮箱已被使用，请重新填入新的邮箱");
            }
        }

        // 如果一切检查通过, 删除验证码缓存并允许注册
        redisService.delMailCode(validator.getEmail());

        return Result.success(200);
    }


    @Override
    public Result findUserByUseridOrEmail(String mark) {
        if (StrUtil.isBlank(mark)) {
            return Result.fail("查询内容不能为空");
        }

        // 使用正则表达式验证邮箱格式
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        boolean isEmail = Pattern.matches(emailRegex, mark);

        return Result.success(this.lambdaQuery()
                .eq(isEmail ? User::getEmail : User::getUserId, mark)
                .one());
    }

    @Override
    public void updateLoginInfo(String userId) {
        // 1. 获取当前时间（登录时间）
        LocalDateTime loginTime = LocalDateTime.now();

        // 2. 更新用户表（如 last_login_time, login_count+1 等）
        userMapper.updateLoginInfo(userId, loginTime);
    }
    /**
     *
     * @param email 用户邮箱
     * @param code 验证码
     * @return 检查结果
     */
    @Override
    public Result EmailDataCheck(String email, String code) {
        // 验证邮箱格式
        if (!isValidEmail(email)) {
            return Result.fail(412, "邮箱格式无效，请检查邮箱地址");
        }
        // 检查验证码是否存在并且有效
        String cachedCode = redisService.getMailCode(email);
        if (cachedCode == null) {
            return Result.fail(413, "验证码无效或已过期");
        }
        // 判断验证码是否正确
        if (!cachedCode.equals(String.valueOf(code))) {
            return Result.fail(414, "验证码错误");
        }
        return Result.success(200);
    }

    /**
     * 校验邮箱格式是否有效
     * @param email 邮箱地址
     * @return 是否有效
     */
    private boolean isValidEmail(String email) {
        String emailRegex = "^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.)+[A-Za-z]{2,}$";
        Pattern pattern = Pattern.compile(emailRegex);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}